﻿using Dapper;
using System;
using BCEntity.OA.WorkflowActive.WorkflowActivityStepReviewer;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.OA.WorkflowActive.WorkflowActivityStepReviewer
{
	/// <summary>
	/// 工作流活动步骤审核人
	/// </summary>
	public class WorkflowActivityStepReviewerData : IWorkflowActivityStepReviewerData
	{
		private readonly IDatabaseContext databaseContext;
		private const string QUERY_EXISTS = @"SELECT 1 FROM oa_workflowactivitystepreviewer";
		private const string QUERY = @"SELECT WorkflowActivityStepReviewerId,WorkflowName,TemplateStepCode,StepCode,CompanyId,DepartmentId,AdminId,OtherUserId,
											NotificationTitle,CreateTime,ReadTime,WorkflowCategoryId,HandleTime,WorkflowActivityId,WorkflowActivityStepId,CategoryCode,
											CategoryName,TemplateCode,TemplateName,WorkflowCode 
										FROM oa_workflowactivitystepreviewer";
		public WorkflowActivityStepReviewerData(IDatabaseContext databaseContext)
		{
			this.databaseContext = databaseContext;
		}
		#region 检查工作流活动步骤审核人是否存在
		public async Task<bool> Exists(long workflowActivityStepReviewerId)
		{
			string sql = string.Format(@"{0} WHERE WorkflowActivityStepReviewerId=?WorkflowActivityStepReviewerId", QUERY_EXISTS);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?WorkflowActivityStepReviewerId", workflowActivityStepReviewerId, DbType.Int64);
			return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
		}
		#endregion

		#region 添加工作流活动步骤审核人
		public async Task<WorkflowActivityStepReviewerEntity> Add(WorkflowActivityStepReviewerEntity entity)
		{
			string sql = SqlCommands.GetInsertSql("oa_workflowactivitystepreviewer", new string[] { "WorkflowName", "TemplateStepCode", "StepCode", "WorkflowCategoryId", 
				"WorkflowActivityId", "WorkflowActivityStepId", "CategoryCode", "CategoryName", "TemplateCode", "TemplateName", "WorkflowCode","CompanyId","DepartmentId",
				"AdminId","OtherUserId" ,"NotificationTitle"});
			sql = string.Format("{0} {1} WHERE WorkflowActivityStepReviewerId=LAST_INSERT_ID();", sql, QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?WorkflowName", entity.WorkflowName?.Trim(), DbType.AnsiString, size: 100);
			parameters.Add("?TemplateStepCode", entity.TemplateStepCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?StepCode", entity.StepCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?WorkflowCategoryId", entity.WorkflowCategoryId, DbType.Int64, size: 20);
			parameters.Add("?WorkflowActivityId", entity.WorkflowActivityId, DbType.Int64, size: 20);
			parameters.Add("?WorkflowActivityStepId", entity.WorkflowActivityStepId, DbType.Int64, size: 20);
			parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
			parameters.Add("?TemplateCode", entity.TemplateCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?TemplateName", entity.TemplateName?.Trim(), DbType.AnsiString, size: 100);
			parameters.Add("?WorkflowCode", entity.WorkflowCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
			parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
			parameters.Add("?AdminId", entity.AdminId, DbType.Int64, size: 20);
			parameters.Add("?OtherUserId", entity.OtherUserId, DbType.Int64, size: 20);
			parameters.Add("?NotificationTitle", entity.NotificationTitle?.Trim(), DbType.AnsiString, size: 200);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityStepReviewerEntity>(sql, parameters, databaseContext.Transaction);

		}
		public async Task<bool> Add(List<WorkflowActivityStepReviewerEntity> entities)
		{
			return await this.databaseContext.Master.InsertAllAsync(entities, "oa_workflowactivitystepreviewer", databaseContext.Transaction) == entities.Count;
		}
		
		#endregion

		#region 修改工作流活动步骤审核人
		public async Task<WorkflowActivityStepReviewerEntity> Update(WorkflowActivityStepReviewerEntity entity)
		{
			string sql = SqlCommands.GetUpdateSql("oa_workflowactivitystepreviewer", new string[] { "WorkflowName", "TemplateStepCode", "StepCode", "CompanyId", "DepartmentId", "AdminId", "OtherUserId", "NotificationTitle", "ReadTime", "WorkflowCategoryId", "HandleTime", "WorkflowActivityId", "WorkflowActivityStepId", "CategoryCode", "CategoryName", "TemplateCode", "TemplateName", "WorkflowCode" }, new string[] { "WorkflowActivityStepReviewerId" });
			sql = string.Format("{0} {1} WHERE WorkflowActivityStepReviewerId=?WorkflowActivityStepReviewerId;", sql, QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?WorkflowActivityStepReviewerId", entity.WorkflowActivityStepReviewerId, DbType.Int64, size: 20);
			parameters.Add("?WorkflowName", entity.WorkflowName?.Trim(), DbType.AnsiString, size: 100);
			parameters.Add("?TemplateStepCode", entity.TemplateStepCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?StepCode", entity.StepCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
			parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32, size: 11);
			parameters.Add("?AdminId", entity.AdminId, DbType.Int64, size: 20);
			parameters.Add("?OtherUserId", entity.OtherUserId, DbType.Int64, size: 20);
			parameters.Add("?NotificationTitle", entity.NotificationTitle?.Trim(), DbType.AnsiString, size: 200);
			parameters.Add("?ReadTime", entity.ReadTime, DbType.DateTime);
			parameters.Add("?WorkflowCategoryId", entity.WorkflowCategoryId, DbType.Int64, size: 20);
			parameters.Add("?HandleTime", entity.HandleTime, DbType.DateTime);
			parameters.Add("?WorkflowActivityId", entity.WorkflowActivityId, DbType.Int64, size: 20);
			parameters.Add("?WorkflowActivityStepId", entity.WorkflowActivityStepId, DbType.Int64, size: 20);
			parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
			parameters.Add("?TemplateCode", entity.TemplateCode?.Trim(), DbType.AnsiString, size: 50);
			parameters.Add("?TemplateName", entity.TemplateName?.Trim(), DbType.AnsiString, size: 100);
			parameters.Add("?WorkflowCode", entity.WorkflowCode?.Trim(), DbType.AnsiString, size: 50);
			return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowActivityStepReviewerEntity>(sql, parameters, databaseContext.Transaction);
		}
		#endregion

		#region 删除工作流活动步骤审核人
		public async Task<bool> Delete(long workflowActivityStepReviewerId)
		{
			string sql = @"DELETE FROM oa_workflowactivitystepreviewer WHERE WorkflowActivityStepReviewerId=?WorkflowActivityStepReviewerId";
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?WorkflowActivityStepReviewerId", workflowActivityStepReviewerId, DbType.Int64);
			return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
		}
		#endregion

		#region 获取工作流活动步骤审核人
		public async Task<WorkflowActivityStepReviewerEntity> GetEntity(long workflowActivityStepReviewerId)
		{
			string sql = string.Format(@"{0} WHERE WorkflowActivityStepReviewerId=?WorkflowActivityStepReviewerId LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?WorkflowActivityStepReviewerId", workflowActivityStepReviewerId, DbType.Int64);
			return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WorkflowActivityStepReviewerEntity>(sql, parameters);
		}
		#endregion

		#region 获取工作流活动步骤审核人
		public async Task<WorkflowActivityStepReviewerEntity> GetEntityByStepId(long workflowActivityStepId)
		{
			string sql = string.Format(@"{0} WHERE WorkflowActivityStepId=?WorkflowActivityStepId LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?WorkflowActivityStepId", workflowActivityStepId, DbType.Int64);
			return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WorkflowActivityStepReviewerEntity>(sql, parameters);
		}
		#endregion
		

		#region 获取工作流活动步骤审核人列表
		public async Task<IEnumerable<WorkflowActivityStepReviewerEntity>> GetList()
		{
			return await this.databaseContext.Slave.QueryAsync<WorkflowActivityStepReviewerEntity>(QUERY);
		}
		#endregion

		#region 获取工作流活动步骤审核人分页
		public async Task<(IEnumerable<WorkflowActivityStepReviewerEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
		{
			List<string> wheres = new List<string>();
			DynamicParameters parameters = new DynamicParameters();

			if (start.HasValue && !end.HasValue)
			{
				wheres.Add("CreateTime>=?Start");
				parameters.Add("?Start", start.Value, DbType.DateTime);
			}
			else if (!start.HasValue && end.HasValue)
			{
				wheres.Add("CreateTime<=?End");
				parameters.Add("?End", end.Value, DbType.DateTime);
			}
			else if (start.HasValue && end.HasValue)
			{
				wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
				parameters.Add("?Start", start.Value, DbType.DateTime);
				parameters.Add("?End", end.Value, DbType.DateTime);
			}
			string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM oa_workflowactivitystepreviewer {1}",
				  QUERY,
				  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
				  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
				  pageSize,
				  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
				  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
			return await this.databaseContext.Slave.QueryMultipleAsync<WorkflowActivityStepReviewerEntity, int>(sql, parameters);
		}
		#endregion

		#region 获取工作量最少的审核人信息
		public async Task<WorkflowActivityStepReviewerEntity> GetWorkMinimumReviewerByCompanyId(int companyId)
        {
			string sql = string.Format(@"{0} WHERE AdminId =(SELECT AdminId FROM oa_workflowactivitystepreviewer
									WHERE HandleTime IS NULL AND CompanyId=?CompanyId
									GROUP BY AdminId
									ORDER BY COUNT(AdminId) DESC LIMIT 1) LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?CompanyId", companyId, DbType.Int32);
			return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WorkflowActivityStepReviewerEntity>(sql, parameters);
		}

        public async Task<WorkflowActivityStepReviewerEntity> GetWorkMinimumReviewerByDepartmentId(int departmentId)
        {
			string sql = string.Format(@"{0} WHERE AdminId =(SELECT AdminId FROM oa_workflowactivitystepreviewer
									WHERE HandleTime IS NULL AND DepartmentId=?DepartmentId
									GROUP BY AdminId
									ORDER BY COUNT(AdminId) DESC LIMIT 1) LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?DepartmentId", departmentId, DbType.Int32);
			return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WorkflowActivityStepReviewerEntity>(sql, parameters);
		}

		public async Task<WorkflowActivityStepReviewerEntity> GetWorkMinimumReviewerByAdminId(List<long> adminIds)
        {
			string sql = string.Format(@"{0} WHERE AdminId =(SELECT AdminId FROM oa_workflowactivitystepreviewer
									WHERE HandleTime IS NULL AND FIND_IN_SET(AdminId,?AdminIds)
									GROUP BY AdminId
									ORDER BY COUNT(AdminId) DESC LIMIT 1) LIMIT 1", QUERY);
			DynamicParameters parameters = new DynamicParameters();
			parameters.Add("?AdminIds", string.Join(',',adminIds), DbType.AnsiString);
			return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WorkflowActivityStepReviewerEntity>(sql, parameters);
		}
		#endregion
	}
}



